package com.zhishiku.filesystem.server.impl;

import com.ruoyi.common.utils.StringUtils;
import com.zhishiku.filesystem.server.MinioService;
import com.zhishiku.filesystem.util.MinioUtil;
import com.zhishiku.filesystem.util.SnowFlakeIdWorker;
import lombok.NonNull;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.Map;

@Service
public class MinioServiceImpl implements MinioService {

    @Autowired
    private MinioUtil minioUtil;

    @Value("${minio.bucket-name}")
    private String bucketName;

    // 雪花算法生成唯一文件名
    private SnowFlakeIdWorker worker = new SnowFlakeIdWorker(1, 1);

    @Override
    public InputStream getFile(String objectPath) throws Exception {
        // 参数校验
        if (StringUtils.isBlank(objectPath)) {
            throw new IllegalArgumentException("文件路径不能为空");
        }

        // 从配置读取默认存储桶
        return minioUtil.getFileInputStream(bucketName, objectPath);
    }

    @Override
    @SneakyThrows
    public Map<String, String> uploadFile(MultipartFile file,@NonNull String fileName){
        // 考虑更换存储桶情况
        minioUtil.bucketExists(bucketName);
        // 生成上传文件名
        String[] split = fileName.split("\\.");
        String mIniFileName = String.valueOf(worker.nextId())+"."+split[split.length-1];
        //上传文件
        return minioUtil.minioUpload(file, mIniFileName, bucketName);
    }

    @Override
    public InputStream downloadFile(String fileName,HttpServletResponse response) {
        return minioUtil.downloadFile( bucketName, fileName, response) ;
    }

    @Override
    public boolean deleteFile(String bucketName,String fileName) {
        if (minioUtil.deleteFile(bucketName,fileName)){
            return true;
        }
        return false;
    }
}